<template>
  <div class="dashboard-container">
    <!-- 顶部统计卡片 -->
    <div class="stats-cards">
      <el-row :gutter="20">
        <el-col :xs="12" :sm="6" :md="6" :lg="6" :xl="6">
          <div class="stat-card">
            <div class="stat-icon exam-icon">
              <el-icon><Document /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">
                <CountUp :end-val="dashboardData.totalExams" :duration="2" />
              </div>
              <div class="stat-label">总考试数</div>
            </div>
          </div>
        </el-col>
        <el-col :xs="12" :sm="6" :md="6" :lg="6" :xl="6">
          <div class="stat-card">
            <div class="stat-icon student-icon">
              <el-icon><User /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">
                <CountUp :end-val="dashboardData.totalStudents" :duration="2" />
              </div>
              <div class="stat-label">总学生数</div>
            </div>
          </div>
        </el-col>
        <el-col :xs="12" :sm="6" :md="6" :lg="6" :xl="6">
          <div class="stat-card">
            <div class="stat-icon question-icon">
              <el-icon><QuestionFilled /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">
                <CountUp :end-val="dashboardData.totalQuestions" :duration="2" />
              </div>
              <div class="stat-label">总题目数</div>
            </div>
          </div>
        </el-col>
        <el-col :xs="12" :sm="6" :md="6" :lg="6" :xl="6">
          <div class="stat-card">
            <div class="stat-icon score-icon">
              <el-icon><TrendCharts /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">
                <CountUp :end-val="dashboardData.averageScore" :duration="2" suffix="%" />
              </div>
              <div class="stat-label">平均分数</div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="chart-section">
      <!-- 班级成绩分布 -->
      <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
        <el-card class="chart-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>班级成绩分布</span>
              <el-button type="text" @click="refreshScoreChart">
                <el-icon><Refresh /></el-icon>
              </el-button>
            </div>
          </template>
          <div ref="scoreChartRef" class="chart-container"></div>
        </el-card>
      </el-col>

      <!-- 答题正确率统计 -->
      <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
        <el-card class="chart-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>答题正确率统计</span>
              <el-button type="text" @click="refreshAccuracyChart">
                <el-icon><Refresh /></el-icon>
              </el-button>
            </div>
          </template>
          <div ref="accuracyChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="chart-section">
      <!-- 考试参与趋势 -->
      <el-col :xs="24" :sm="24" :md="16" :lg="16" :xl="16">
        <el-card class="chart-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>考试参与趋势</span>
              <el-button type="text" @click="refreshTrendChart">
                <el-icon><Refresh /></el-icon>
              </el-button>
            </div>
          </template>
          <div ref="trendChartRef" class="chart-container"></div>
        </el-card>
      </el-col>

      <!-- 最近考试列表 -->
      <el-col :xs="24" :sm="24" :md="8" :lg="8" :xl="8">
        <el-card class="chart-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>最近考试</span>
              <el-button type="text" @click="loadRecentExams">
                <el-icon><Refresh /></el-icon>
              </el-button>
            </div>
          </template>
          <div class="recent-exams">
            <div v-for="exam in recentExams" :key="exam.examId" class="exam-item">
              <div class="exam-info">
                <div class="exam-title">{{ exam.title }}</div>
                <div class="exam-meta">
                  <span class="exam-date">{{ formatDate(exam.createTime) }}</span>
                  <span class="exam-participants">{{ exam.participantCount }}人参与</span>
                </div>
              </div>
              <div class="exam-score">
                <el-tag :type="getScoreTagType(exam.avgScore)">
                  {{ exam.avgScore }}%
                </el-tag>
              </div>
            </div>
            <div v-if="recentExams.length === 0" class="no-data">
              <el-empty description="暂无考试数据" />
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup name="Dashboard" lang="ts">
import { ref, onMounted, nextTick, onBeforeUnmount } from 'vue';
import * as echarts from 'echarts';
import { Document, User, QuestionFilled, TrendCharts, Refresh } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import CountUp from 'vue-countup-v3';

// 响应式数据
const dashboardData = ref({
  totalExams: 156,
  totalStudents: 2340,
  totalQuestions: 8750,
  averageScore: 85
});

const recentExams = ref([]);

// 图表引用
const scoreChartRef = ref();
const accuracyChartRef = ref();
const trendChartRef = ref();

// 图表实例
let scoreChart: echarts.ECharts;
let accuracyChart: echarts.ECharts;
let trendChart: echarts.ECharts;

// 初始化图表
const initCharts = () => {
  nextTick(() => {
    initScoreChart();
    initAccuracyChart();
    initTrendChart();
  });
};

// 初始化成绩分布图表
const initScoreChart = () => {
  if (scoreChartRef.value) {
    scoreChart = echarts.init(scoreChartRef.value);
    const option = {
      title: {
        text: '成绩分布',
        left: 'center',
        textStyle: {
          fontSize: 14,
          color: '#666'
        }
      },
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        left: 'left',
        data: ['优秀(90-100)', '良好(80-89)', '中等(70-79)', '及格(60-69)', '不及格(<60)']
      },
      series: [
        {
          name: '成绩分布',
          type: 'pie',
          radius: '50%',
          data: [
            { value: 35, name: '优秀(90-100)' },
            { value: 28, name: '良好(80-89)' },
            { value: 20, name: '中等(70-79)' },
            { value: 12, name: '及格(60-69)' },
            { value: 5, name: '不及格(<60)' }
          ],
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ],
      color: ['#67C23A', '#409EFF', '#E6A23C', '#F56C6C', '#909399']
    };
    scoreChart.setOption(option);
  }
};

// 初始化正确率统计图表
const initAccuracyChart = () => {
  if (accuracyChartRef.value) {
    accuracyChart = echarts.init(accuracyChartRef.value);
    const option = {
      title: {
        text: '题型正确率',
        left: 'center',
        textStyle: {
          fontSize: 14,
          color: '#666'
        }
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      xAxis: {
        type: 'category',
        data: ['单选题', '多选题', '判断题', '填空题', '简答题']
      },
      yAxis: {
        type: 'value',
        max: 100,
        axisLabel: {
          formatter: '{value}%'
        }
      },
      series: [
        {
          name: '正确率',
          type: 'bar',
          data: [85, 72, 90, 68, 75],
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#83bff6' },
              { offset: 0.5, color: '#188df0' },
              { offset: 1, color: '#188df0' }
            ])
          },
          emphasis: {
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#2378f7' },
                { offset: 0.7, color: '#2378f7' },
                { offset: 1, color: '#83bff6' }
              ])
            }
          }
        }
      ]
    };
    accuracyChart.setOption(option);
  }
};

// 初始化趋势图表
const initTrendChart = () => {
  if (trendChartRef.value) {
    trendChart = echarts.init(trendChartRef.value);
    const option = {
    //   title: {
    //     text: '考试参与趋势',
    //     left: 'center',
    //     textStyle: {
    //       fontSize: 14,
    //       color: '#666'
    //     }
    //   },
      tooltip: {
        trigger: 'axis'
      },
      legend: {
        data: ['参与人数', '平均分']
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: ['1月', '2月', '3月', '4月', '5月', '6月']
      },
      yAxis: [
        {
          type: 'value',
          name: '参与人数',
          position: 'left'
        },
        {
          type: 'value',
          name: '平均分',
          position: 'right',
          max: 100
        }
      ],
      series: [
        {
          name: '参与人数',
          type: 'line',
          yAxisIndex: 0,
          data: [120, 132, 101, 134, 90, 230],
          smooth: true,
          itemStyle: {
            color: '#409EFF'
          }
        },
        {
          name: '平均分',
          type: 'line',
          yAxisIndex: 1,
          data: [78, 82, 85, 79, 88, 86],
          smooth: true,
          itemStyle: {
            color: '#67C23A'
          }
        }
      ]
    };
    trendChart.setOption(option);
  }
};

// 加载仪表盘数据
const loadDashboardData = async () => {
  try {
    // 模拟数据，实际应该调用API
    dashboardData.value = {
      totalExams: 25,
      totalStudents: 156,
      totalQuestions: 450,
      avgScore: 82
    };
    
    // 加载最近考试数据
    recentExams.value = [
      {
        examId: 1,
        title: '期中考试',
        createTime: '2025-01-15',
        participantCount: 45,
        avgScore: 85
      },
      {
        examId: 2,
        title: '单元测试一',
        createTime: '2025-01-10',
        participantCount: 38,
        avgScore: 78
      },
      {
        examId: 3,
        title: '随堂练习',
        createTime: '2025-01-08',
        participantCount: 42,
        avgScore: 92
      }
    ];
  } catch (error) {
    console.error('加载仪表盘数据失败:', error);
    ElMessage.error('加载数据失败');
  }
};

// 刷新图表
const refreshScoreChart = () => {
  if (scoreChart) {
    scoreChart.resize();
  }
};

const refreshAccuracyChart = () => {
  if (accuracyChart) {
    accuracyChart.resize();
  }
};

const refreshTrendChart = () => {
  if (trendChart) {
    trendChart.resize();
  }
};

// 加载最近考试
const loadRecentExams = () => {
  loadDashboardData();
};

// 格式化日期
const formatDate = (dateStr: string) => {
  const date = new Date(dateStr);
  return `${date.getMonth() + 1}月${date.getDate()}日`;
};

// 获取分数标签类型
const getScoreTagType = (score: number) => {
  if (score >= 90) return 'success';
  if (score >= 80) return '';
  if (score >= 70) return 'warning';
  return 'danger';
};

// 窗口大小变化时重新调整图表
const handleResize = () => {
  if (scoreChart) scoreChart.resize();
  if (accuracyChart) accuracyChart.resize();
  if (trendChart) trendChart.resize();
};

// 生命周期
onMounted(() => {
  loadDashboardData();
  initCharts();
  window.addEventListener('resize', handleResize);
});

// 组件卸载时清理
onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize);
  if (scoreChart) scoreChart.dispose();
  if (accuracyChart) accuracyChart.dispose();
  if (trendChart) trendChart.dispose();
});
</script>

<style scoped lang="scss">
.dashboard-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 84px);

  .stats-cards {
    margin-bottom: 20px;

    .stat-card {
      background: white;
      border-radius: 8px;
      padding: 20px;
      display: flex;
      align-items: center;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
      transition: all 0.3s;
      margin-bottom: 20px;

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 20px 0 rgba(0, 0, 0, 0.15);
      }

      .stat-icon {
        width: 60px;
        height: 60px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 16px;
        font-size: 24px;
        color: white;

        &.exam-icon {
          background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        }

        &.student-icon {
          background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
        }

        &.question-icon {
          background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
        }

        &.score-icon {
          background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
        }
      }

      .stat-content {
          .stat-value {
            font-size: 28px;
            font-weight: bold;
            color: #303133;
            line-height: 1;
          }

          .stat-label {
            font-size: 14px;
            color: #909399;
            margin-top: 4px;
          }
        }
    }
  }

  .chart-section {
    margin-bottom: 20px;

    .chart-card {
      height: 400px;

      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        font-weight: bold;
        color: #303133;
      }

      .chart-container {
        height: 320px;
        width: 100%;
      }

      .recent-exams {
        height: 320px;
        overflow-y: auto;

        .exam-item {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 12px 0;
          border-bottom: 1px solid #f0f0f0;

          &:last-child {
            border-bottom: none;
          }

          .exam-info {
            flex: 1;

            .exam-title {
              font-size: 14px;
              font-weight: 500;
              color: #303133;
              margin-bottom: 4px;
            }

            .exam-meta {
              font-size: 12px;
              color: #909399;

              .exam-date {
                margin-right: 12px;
              }
            }
          }

          .exam-score {
            margin-left: 12px;
          }
        }

        .no-data {
          display: flex;
          align-items: center;
          justify-content: center;
          height: 100%;
        }
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .dashboard-container {
    padding: 10px;

    .stats-cards {
      .stat-card {
        padding: 15px;

        .stat-icon {
          width: 50px;
          height: 50px;
          font-size: 20px;
          margin-right: 12px;
        }

        .stat-content {
          .stat-value {
            font-size: 24px;
          }

          .stat-label {
            font-size: 12px;
          }
        }
      }
    }

    .chart-section {
      .chart-card {
        height: 350px;
        margin-bottom: 15px;

        .chart-container {
          height: 270px;
        }

        .recent-exams {
          height: 270px;
        }
      }
    }
  }
}
</style>
